<template>
  <div class="article-list-box duan-list-box">
    <div class="btn-box m-b-s m-t-s">
      <span class="title">授权信息</span>
      <el-button type="primary" plain size="mini" @click="addForm">新增</el-button>
    </div>

    <template v-if="dataList.length > 0">
      <div v-for="(item, index) in dataList" :key="index" class="limit-item-box" :class="index % 2 == 1 ? 'bg-gray' : ''">
        <el-form :model="item" ref="baseInfo" size="small" label-position="left" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="授权类型">
                <el-select class="full-width" v-model="item.authType" placeholder="请选择" :disabled="true">
                  <el-option label="明授" value="1" />
                  <el-option label="暗授" value="0" />
                  <el-option label="代申请" value="2" />
                  <el-option label="建单权限" value="3" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="授权时间">
                <el-date-picker class="full-width" v-model="item.updateTime" type="datetime" :readonly="true" />
              </el-form-item>
            </el-col>
            <template v-if="item.authType != 3">
              <el-col :span="12">
                <el-form-item label="授权人">
                  <el-input class="full-width" v-model="item.auditorsUserName" :readonly="true" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="被授权人">
                  <el-input class="full-width" v-model="item.authorizedUserName" :readonly="true" />
                </el-form-item>
              </el-col>
            </template>

            <template v-if="item.authType == 3">
              <el-col :span="24">
                <el-form-item label="授权角色">
                  <el-select class="full-width" :value="item.authorizedUser ? item.authorizedUser.split(',') : []" multiple disabled>
                    <el-option v-for="(item, index) in roleList" :key="index" :label="item.value" :value="item.key" />
                  </el-select>
                </el-form-item>
              </el-col>
            </template>
            <template v-if="item.authType != 2 && item.authType != 3">
              <el-col :span="12">
                <el-form-item label="节点">
                  <el-input class="full-width" v-model="item.nodeName" :readonly="true" />
                </el-form-item>
              </el-col>
            </template>
            <el-col :span="12">
              <el-form-item label="备注">
                <el-input type="textarea" class="full-width" :autosize="{ minRows: 1, maxRows: 1 }" placeholder="请输入备注" v-model="item.remark" maxlength="50" :readonly="true" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="">
                <el-button class="f-right m-l-s" plain type="danger" size="mini" @click="deleteItem(item)">删除</el-button>
                <el-button class="f-right" plain type="primary" size="mini" @click="editItem(item)">编辑</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </template>
    <template v-else>
      <div class="no-content-box">暂无授权信息</div>
    </template>
    <div class="pagination">
      <el-pagination v-if="total > pageSize" class="page-box" @current-change="pageChange" layout="prev, pager, next" :page-size="pageSize" :total="total" :current-page="currentPage" />
    </div>

    <el-dialog title="授权管理" :visible.sync="dialogShow" width="600px">
      <el-form ref="auditForm" size="small" label-position="left" :model="itemData" label-width="90px" style="padding: 0px 20px" @submit.native.prevent>
        <el-form-item label="授权类型" prop="authType" :rules="{ required: true, message: '请选择授权类型', trigger: ['blur', 'change'] }">
          <el-select class="full-width" v-model="itemData.authType" placeholder="请选择">
            <el-option label="明授" value="1"></el-option>
            <el-option label="暗授" value="0"></el-option>
            <el-option label="代申请" value="2"></el-option>
            <el-option label="建单权限" value="3"></el-option>
          </el-select>
        </el-form-item>
        <template v-if="itemData.authType != 3 && itemData.authType">
          <el-form-item label="授权人" prop="auditorsUser" :rules="{ required: true, message: '请选择审批人', trigger: ['blur', 'change'] }">
            <el-select class="full-width" v-model="itemData.auditorsUser" placeholder="请输入查询" remote filterable reserve-keyword :remote-method="remoteMethod" @change="getUserName('auditorsUser', 'auditorsUserName', 'personList')">
              <el-option v-for="item in personList" :key="item.value" :label="item.employeeName" :value="item.primaryKey" />
            </el-select>
          </el-form-item>
          <el-form-item label="被授权人" prop="authorizedUser" :rules="{ required: true, message: '请选择被授权人', trigger: ['blur', 'change'] }">
            <el-select class="full-width" v-model="itemData.authorizedUser" placeholder="请输入查询" remote filterable reserve-keyword :remote-method="remoteToMethod" @change="getUserName('authorizedUser', 'authorizedUserName', 'personToList')">
              <el-option v-for="item in personToList" :key="item.value" :label="item.employeeName" :value="item.primaryKey" />
            </el-select>
          </el-form-item>
        </template>
        <template v-if="itemData.authType == 3">
          <el-form-item label="授权角色" prop="authorizedUserRole" filterable :rules="{ required: true, message: '请选择授权角色', trigger: ['blur', 'change'] }">
            <el-select class="full-width" v-model="itemData.authorizedUserRoleArr" placeholder="请选择授权角色" multiple @change="changeAuthorizedUserRoleArr">
              <el-option v-for="(item, index) in roleList" :key="index" :label="item.value" :value="item.key"> </el-option>
            </el-select>
          </el-form-item>
        </template>
        <!-- 代申请不需要选择节点 -->
        <el-form-item label="节点" v-if="itemData.authType != 2 && itemData.authType != 3 && itemData.authType" :rules="{ required: true, message: '请选择节点', trigger: ['blur', 'change'] }">
          <el-select class="full-width" v-model="itemData.nodeCode" placeholder="请选择" clearable filterable>
            <el-option v-for="item in nideCodeList" :key="item.primaryKey" :label="item.nodeName" :value="item.primaryKey" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" class="full-width" :autosize="{ minRows: 3, maxRows: 6 }" placeholder="请输入备注" v-model="itemData.remark" maxlength="50" show-word-limit />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogShow = false" size="mini" class="el-button-reset">取 消</el-button>
        <el-button type="primary" size="mini" @click="creatImpower">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import { impowerList, impowerDelete, impowerCreate, impowerUpdate, getNodeCode, apiGetGuys, apiRoleList } from '../../../api/process';
  import { formValid, formatDate } from '@/common/js/utils';

  export default {
    props: ['processData'],
    data() {
      return {
        dataList: [],
        total: 0,
        pageSize: 20,
        currentPage: 1,
        dialogShow: false,
        itemData: {
          auditorsUser: '',
          auditorsUserName: '',
          authorizedUser: '',
          authorizedUserName: '',
          authorizedUserRole: '',
          authorizedUserRoleArr: [],
          authType: '0',
          remark: '',
          nodeCode: '',
        },
        personList: [],
        personToList: [],
        nideCodeList: [],
        roleList: [],
      };
    },
    mounted() {
      this.getNodeCodeList();
      this.getRoleList();
    },
    filters: {
      formatDate: formatDate,
    },
    methods: {
      async getRoleList() {
        let res = await apiRoleList();
        this.roleList = res.rows;
      },
      //节点code
      async getNodeCodeList(type) {
        let res = await getNodeCode({
          processCode: this.$route.query.key,
        });
        this.nideCodeList = res.rows || [];
      },
      //列表数据源
      async getInfo(type) {
        if (!type) {
          this.currentPage = 1;
        }
        let res = await impowerList({
          formType: this.$route.query.tab,
          pageSize: this.pageSize,
          currentPage: this.currentPage,
          processCode: this.$route.query.key,
        });
        res.rows.forEach(item => {
          item.nodeName = this.getNodeName(item.nodeCode);
        });
        this.dataList = res.rows || [];
        this.total = res.total;
      },
      //添加
      addForm() {
        this.clearData();
        this.dialogShow = true;
      },
      //编辑
      editItem(row) {
        row.authorizedUserRole = '';
        row.authorizedUserRoleArr = [];
        this.itemData = Object.assign({}, row);
        if (this.itemData.authType == 3) {
          this.itemData.authorizedUserRole = this.itemData.authorizedUser;
          this.itemData.authorizedUserRoleArr = this.itemData.authorizedUser ? this.itemData.authorizedUser.split(',') : [];
          this.itemData.authorizedUser = '';
          this.itemData.authorizedUserName = '';
        }
        if (this.itemData.authType != 3) {
          this.remoteMethod(row.auditorsUserName);
          this.remoteToMethod(row.authorizedUserName);
        }
        this.dialogShow = true;
      },
      //删除
      async deleteItem(rows) {
        this.$confirm('确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            let res = await impowerDelete({ primaryKey: rows.primaryKey });
            if (res.success) {
              this.getInfo('more');
              this.$message.success('删除成功!');
            } else {
              this.$message.error(res.message);
            }
          })
          .catch(() => {});
      },
      //分页
      pageChange(size) {
        this.currentPage = size;
        this.getInfo('more');
      },
      //创建授权
      creatImpower() {
        formValid(this, 'auditForm', this.saveBaseFn);
      },
      async saveBaseFn() {
        let itemData = Object.assign({}, this.itemData);
        itemData.processCode = this.$route.query.key;

        // 代申请时节点为'null'
        if (itemData.authType == 2) {
          itemData.nodeCode = 'null';
        }
        if (itemData.authType == 3) {
          itemData.authorizedUser = itemData.authorizedUserRole;
          itemData.authorizedUserName = '';
        }
        let res = itemData.primaryKey ? await impowerUpdate(itemData) : await impowerCreate(itemData);
        let statusName = res.success ? 'success' : 'error';
        this.$message({ type: statusName, message: res.message });
        this.dialogShow = false;
        res.success && this.getInfo();
      },
      //还原数据
      clearData() {
        for (var i in this.itemData) {
          this.itemData[i] = '';
        }
      },
      //查询人员
      async remoteMethod(val) {
        if (!this.processData && !this.processData.strucCode) {
          return;
        }

        let res = await apiGetGuys({
          structureCode: this.processData.strucCode,
          employeeName: val,
        });
        this.personList = res.rows || [];
      },
      async remoteToMethod(val) {
        if (!this.processData && !this.processData.strucCode) {
          return;
        }

        let res = await apiGetGuys({
          structureCode: this.processData.strucCode,
          employeeName: val,
        });
        this.personToList = res.rows || [];
      },
      //授权人的名字汉字
      getUserName(param, name, listName) {
        this[listName].forEach(item => {
          if (item.primaryKey == this.itemData[param]) {
            this.itemData[name] = item.employeeName;
          }
        });
      },
      //get节点汉字
      getNodeName(code) {
        let name = '';
        this.nideCodeList.forEach(item => {
          if (item.primaryKey == code) {
            name = item.nodeName;
          }
        });
        return name;
      },
      changeAuthorizedUserRoleArr() {
        this.itemData.authorizedUserRole = this.itemData.authorizedUserRoleArr.length ? this.itemData.authorizedUserRoleArr.join(',') : '';
      },
    },
  };
</script>

<style lang="scss" scoped>
  .file-font-box .content-box .card-title {
    overflow: hidden;
    font-size: 14px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    word-break: break-all;
    width: 430px;
  }
  .file-font-box .content-box .card-time {
    flex: 2;
  }
  .btn-box {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .title {
      font-size: 16px;
      font-weight: 900;
    }
  }
  .limit-item-box {
    overflow: hidden;
    padding-top: 10px;
  }
  .bg-gray {
    background: #fcf9f9;
  }
</style>
